package com.lingz.manager.modules.camera.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Author: hanyuhang
 * @Description:
 * @Date:Create: 2022/9/24 14:24
 * @Modify:
 */
@Component
public class CommonUtils {

    @Value("${media.dir}")
    private String dir;

    @Value("${media.clientDir}")
    private String clientPath;

    public Map<String, String> upload(MultipartFile file, String path) throws UnknownHostException {
        if (file == null) {
            throw new RuntimeException("请选择你要上传的文件");
        }
        if (file.getSize() > 1024 * 1024 * 5000) {
            throw new RuntimeException("文件大小不能大于500M");
        }
        //获取文件后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1, file.getOriginalFilename().length());

        String savePath = dir;
        savePath = savePath +"/"+path;
        File savePathFile = new File(savePath);
        if (!savePathFile.exists()) {
            //若不存在该目录，则创建目录
            savePathFile.mkdir();
        }
        //通过UUID生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String filename = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
        try {
            //将文件保存指定目录
            file.transferTo(new File(savePath + "/" + filename));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("保存文件异常");
        }
        // 获取当前的IP服务的IP地址
        Map<String, String> map = new HashMap<>();
        map.put("filePath", clientPath + "/" + path + "/" + filename);
        //map.put("fileSize", size);
        map.put("fileName", filename);
        map.put("fileNameOld", originalFilename);
        map.put("fileLocalPath", savePath + "/" + filename);
        //返回文件名称
        return map;
    }

}
